package com.ddpt.platform.common.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;

public class IpBelongWithinJuheUtil {

    public static final String Juhe_IP_Belong_URL = "http://apis.juhe.cn/ip/ipNew";
    public static final String appKey = "07214759f09e71fa19eff1697ec45d35";

    public static String getIpBelongWithinJuhe(String ip) {

        //获取IP所属区域
        String resultStr = HttpUtil.get(Juhe_IP_Belong_URL + "?ip=" + ip + "&key=" + appKey);
        System.out.println("聚合数据查询IP地址返回值:{}"+ resultStr);
        JSONObject obj = JSONUtil.parseObj(resultStr);
        if (obj.getInt("resultcode") != 200) {
            return "聚合数据查询IP地址失败";
        }

        JSONObject result = obj.getJSONObject("result");
        if (ObjectUtil.isNull(result)) {
            return "聚合数据查询IP地址失败";
        }

        String province = result.getStr("Province");
        String city = result.getStr("City");
        String isp = result.getStr("Isp");

        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(province)) {
            sb.append(province);
        }
        if (StringUtils.isNotBlank(city)) {
            sb.append(city);
        }
        if (StringUtils.isNotBlank(isp)) {
            sb.append(isp);
        }


        return sb.toString();
    }

}
